<!--
 * @Description: In User Settings Edit
 * @Author: your name
 * @Date: 2019-08-01 15:35:09
 * @LastEditTime: 2020-03-23 23:30:15
 * @LastEditors: Please set LastEditors
 -->
<!doctype html>
<html>

<head>
	<meta charset="utf-8">
	<meta name="viewport"
		content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0,viewport-fit=cover" />
	<meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
	<title>Hello APP</title>
	<link rel="stylesheet" type="text/css" href="../css/vant.css">
	<link rel="stylesheet" type="text/css" href="../css/base.css" />
	<script type="text/javascript" src="../script/jquery.js"></script>
	<script type="text/javascript" src="../script/vue.min.js"></script>
	<script type="text/javascript" src="../script/vant.min.js"></script>
	<script type="text/javascript" src="../script/fastclick.js"></script>
	<script type="text/javascript" src="../script/base.js"></script>
	<script type="text/javascript" src="../script/db.js"></script>
	<script type="text/javascript" src="../script/jquery.signalR-2.4.1.min.js"></script>
	<script>
		var scriptBlock = document.createElement('script');
		scriptBlock.src = 'http://' + APP.serverIP() + '/signalr/hubs';
		document.getElementsByTagName('head')[0].appendChild(scriptBlock);
	</script>
	<script type="text/javascript" src="../script/signalr-mediate.js"></script>
	<style type="text/css">
		body {
			background: #efefef;
		}

		.body-no-head {
			height: calc(100% - 50px);
			position: relative;
		}

		.van-info {
			border: 1px solid #f44;
		}
	</style>
</head>

<body>
	<div id="app" v-cloak>

		<van-tabbar inactive-color="#9e9e9e" active-color="#003cff" v-model="tabbarActive" @change="changeTabbar">
			<van-tabbar-item icon="home-o">主页</van-tabbar-item>
			<van-tabbar-item icon="chat-o" :info="dot || ''">消息</van-tabbar-item>
			<van-tabbar-item icon="user-o">我的</van-tabbar-item>
		</van-tabbar>
	</div>
</body>
<script type="text/javascript">
	var vm;
	apiready = function () {

		DB.initDatabase(function () {
			DB.createTable(function () {

			});
		})

		var mine;
		var isOpenChatList = false;

		var friend = '';
		var groups = '';

		APP.exitApp();

		api.addEventListener({
			name: 'setUnRedMsg'
		}, function (ret, err) {
			vm.dot = ret.value.dot;
		});

		api.addEventListener({
			name: 'getUnReadMsgRepeat'
		}, function (ret, err) {
			APP.ajax('getGroupList', { userID: APP.getUserInfo().UserID }, function (res) {
				groups = [];
				for (var i = 0; i < res.ds.length; i++) {
					groups.push({
						groupname: res.ds[i].GroupName,
						id: res.ds[i].GroupID.toString(),
						avatar: "../image/group.png" //群组头像
					})
				}
				vm.getUnReadMsg();
			})
		});



		api.addEventListener({
			name: 'openChatList'
		}, function (ret, err) {
			isOpenChatList = ret.value.isOpenChatList;
		});

		api.addEventListener({
			name: 'sendMineMsg'
		}, function (ret, err) {
			var msgObj = ret.value.msgObj;

			var sendmsg = function () {
				if (msgObj.type == 'friend') {
					$.signalrApi.server.chatMsg(mine.contextIDs, mine.id, msgObj.toUserID, msgObj.content);
				}
				else {
					$.signalrApi.server.groupMsg(mine.contextIDs, mine.id, msgObj.toUserID, msgObj.content);
				}
			}



			try {
				$.signalrApi.server.clientLive();
				sendmsg();
			} catch (e) {
				$.signalrApi.start(function () {
					$.signalrApi.server.clientConnect(APP.getUserInfo().UserID);
					setTimeout(function () {
						sendmsg();
					}, 500)
				});
			}


		});

		var ajpush = api.require('ajpush');

		function listenJPush() {
			var ListenerType = '';
			if (api.systemType == "android") {
				ListenerType = 'appintent';
				ajpush.init(function (ret) {
					var param = { alias: APP.getUserInfo().UserID };
					ajpush.bindAliasAndTags(param, function (ret) {

					});
				});
			} else if (api.systemType == "ios") {
				ListenerType = 'noticeclicked';
				var param = { alias: APP.getUserInfo().UserID };
				ajpush.bindAliasAndTags(param, function (ret) {

				});
			}

			api.addEventListener({ name: ListenerType }, function (ret, err) {
				// console.log(JSON.stringify(ret))
				var data = null;
				// 2025.2.15修改
				// if (api.systemType == "android") {
				// 	data = ret.appParam.ajpush.extra.data;
				// } else {
				// 	data = ret.value.extra.data;
				// }

				if (data) {
					var data_json = JSON.parse(data);
					if (data_json.type == 'chatmsg') {
						APP.ajax('getInfoByID', { msgID: data_json.msg, type: 1 }, function (res) {
							var row = {
								id: res.ds[0].UserID.toString(),
								groupname: '',
								username: res.ds[0].UserName,
								avatar: res.ds[0].HeadImg,
								type: 'friend'
							}
							api.openWin({
								name: 'chatListDetail',
								url: 'chat/chatListDetail.html',
								reload: true,
								slidBackEnabled: false,
								allowEdit:true,
								pageParam: {
									row: row
								}
							})
						})
					} else if (data_json.type == 'groupmsg') {
						APP.ajax('getInfoByID', { msgID: data_json.msg, type: 2 }, function (res) {
							var row = {
								id: res.ds[0].GroupID.toString(),
								groupname: res.ds[0].GroupName,
								username: '',
								avatar: '../../image/ql.png',
								type: 'group'
							}
							api.openWin({
								name: 'chatListDetail',
								url: 'chat/chatListDetail.html',
								reload: true,
								slidBackEnabled: false,
								allowEdit:true,
								pageParam: {
									row: row
								}
							})
						})
					}
				}

			})
		}

		listenJPush();


		var recMp3 = api.require('recMp3');
		var audioStreamer = api.require('audioStreamer');


		function ping(ip) {
			if (api.connectionType !== 'none') {
				// var img = new Image();
				// var start = new Date().getTime();
				// var flag = false;
				// var hasFinish = false;
				// img.onload = function () {
				// 	if (!hasFinish) {
				// 		flag = true;
				// 		hasFinish = true;
				// 		img.src = 'X:\\';
				// 		console.log('Ping ' + ip + ' success. ');

				// 		if (window.localStorage.getItem('serverIP') != ip) {
				// 			window.localStorage.setItem('serverIP', ip);
				// 			APP.serverIP = ip;
				// 			clearInterval(signalrTimer);
				// 			setTimeout(function () {
				// 				signalRHelper();
				// 			}, 2000)

				// 		} else {
				// 			$.signalrApi.start(function () {
				// 				var userInfo = APP.getUserInfo();
				// 				$.signalrApi.server.clientConnect(userInfo.UserID);
				// 			});
				// 		}
				// 	}
				// };
				// img.onerror = function () {
				// 	if (!hasFinish) {
				// 		flag = true;
				// 		hasFinish = true;
				// 		img.src = 'X:\\';
				// 		console.log('Ping ' + ip + ' success. ');
				// 		if (window.localStorage.getItem('serverIP') != ip) {
				// 			window.localStorage.setItem('serverIP', ip);
				// 			APP.serverIP = ip;
				// 			clearInterval(signalrTimer);
				// 			setTimeout(function () {
				// 				signalRHelper();
				// 			}, 2000)
				// 		} else {
				// 			$.signalrApi.start(function () {
				// 				var userInfo = APP.getUserInfo();
				// 				$.signalrApi.server.clientConnect(userInfo.UserID);
				// 			});
				// 		}
				// 	}
				// };
				// img.src = 'http://' + ip + '/' + start;
				// var timer = setTimeout(function () {
				// 	if (!flag) {
				// 		hasFinish = true;
				// 		img.src = 'X://';
				// 		flag = false;
				// 		console.log('Ping ' + ip + ' fail. ');
				// 	}
				// }, 1500);


				api.ajax({
					url: 'http://' + ip + '/Frame/SqlData?cmdname=ConnectionTest',
					data: {
						values: {}
					},
					timeout: 20,
					method: 'post',
					dataType: 'json'
				}, function (ret, err) {
					if (ret) {
						if (window.localStorage.getItem('serverIP') != ip) {
							window.localStorage.setItem('serverIP', ip);
							// APP.serverIP = ip;
							clearInterval(signalrTimer);
							setTimeout(function () {
								signalRHelper();
							}, 2000)
						} else {
							$.signalrApi.start(function () {
								var userInfo = APP.getUserInfo();
								$.signalrApi.server.clientConnect(userInfo.UserID);
							});
						}
					} else {

					}
				});



			} else {
				console.log('Ping ' + ip + ' fail. without connection');
			}




		}

		var signalrTimer = null;

		$.clientCallBacks = {};
		var signalRHelper = function () {
			$.signalrApi({
				serverUrl: "http://" + APP.serverIP(),
				clientHub: "IMHub",
				clientEvents: [
					{
						name: "onClientConnect",
						method: function (data) {
							$.clientCallBacks["onClientConnect"](data);
						}
					},
					{
						name: "onChatMsg",
						method: function (userId, msg, timestap) {
							$.clientCallBacks["onChatMsg"](userId, msg, timestap);
						}
					},
					{
						name: "onGroupMsg",
						method: function (userId, groupId, msg, timestap) {
							$.clientCallBacks["onGroupMsg"](userId, groupId, msg, timestap);
						}
					},
					{
						name: "onUserOnlineNotify",
						method: function (userInfo) {
							$.clientCallBacks["onUserOnlineNotify"](userInfo);
						}
					},
					{
						name: "onUserOfflineNotify",
						method: function (userId) {
							$.clientCallBacks["onUserOfflineNotify"](userId);
						}
					}
				]
			});
			//socket连接
			function signalrConnect() {
				$.signalrApi.start(function () {
					$.signalrApi.server.clientConnect(APP.getUserInfo().UserID);
				});
			}
			signalrConnect();

			signalrTimer = setInterval(function () {
				try {
					$.signalrApi.server.clientLive();
				} catch (e) {
					ping(APP.serverIP1);
					ping(APP.serverIP2);


				}

			}, 2000);
		}








		vm = new Vue({
			el: '#app',
			data: {
				showLoading: false,
				tabbarActive: 0,
				dot: 0
			},
			created: function () {
				var that = this;
				if (api.safeArea.bottom) {
					setTimeout(function () {
						$('.van-tabbar').css({
							'height': 50 + api.safeArea.bottom + 'px',
							'padding-bottom': api.safeArea.bottom -20+ 'px'
						})
					}, 300)

				}

				that.initChat();
				api.openFrame({
					name: 'index',
					url: './index.html',
					rect: {
						x: 0,
						y: 0,
						w: api.winWidth,
						h: api.winHeight - 50 - api.safeArea.bottom
					}
				});


				// that.checkNewAPP();
			},
			methods: {
				checkNewAPP: function () {
					var that = this;
					var mam = api.require('mam');
					mam.checkUpdate(function (ret, err) {
						if (ret) {

							if (ret.result.update) {
								api.openFrame({
									name: 'updateAPP',
									url: 'common/updateAPP.html',
									bgColor: 'rgba(255,255,255,0)',
									rect: {
										x: 0,
										y: 0,
										w: api.winWidth,
										h: api.winHeight
									},
									pageParam: {
										updateData: ret.result
									}
								});
							}
						}
					});
				},
				initChat: function () {
					var that = this;
					APP.ajax('GetChatUser', { userID: APP.getUserInfo().UserID }, function (res) {
						userData = res.ds[0];
						mine = {
							username: res.ds[0].UserName,
							id: res.ds[0].UserID.toString(),
							status: "online",
							sign: res.ds[0].Sign,
							avatar: res.ds[0].HeadImg
						}
						var friendInfo = [{
							"groupname": "劳伦斯用户",
							id: 1
						}];

						groups = [];
						friend = [];
						//用户列表
						for (var i = 0; i < res.ds1.length; i++) {
							friend.push({
								username: res.ds1[i].UserName,
								id: res.ds1[i].UserID.toString(),
								status: res.ds1[i].ContextIDs ? "online" : 'offline',
								sign: res.ds1[i].Sign,
								avatar: res.ds1[i].HeadImg,
								contextIDs: res.ds1[i].ContextIDs
							})
						}
						//群列表
						for (var i = 0; i < res.ds2.length; i++) {
							groups.push({
								groupname: res.ds2[i].GroupName,
								id: res.ds2[i].GroupID.toString(),
								avatar: "../../image/ql.png" //群组头像
							})
						}

						friendInfo[0].list = friend;

						$.clientCallBacks["onClientConnect"] = function (contextID) {
							mine["contextIDs"] = contextID;
						}
						$.clientCallBacks["onChatMsg"] = function (userId, msg, timestamp) {
							var fs = [];
							for (var u in friend) {
								if (friend[u].id == userId) {
									fs.push(friend[u])
								}
							}
							if (fs.length > 0) {
								var msgObj = {
									groupname: '',
									username: fs[0].username,
									avatar: fs[0].avatar,
									id: fs[0].id,
									type: "friend", //聊天窗口来源类型，从发送消息传递的to里面获取
									content: msg,
									cid: 0,  //消息id，可不传。除非你要对消息进行一些操作（如撤回）
									mine: false,  //是否我发送的消息，如果为true，则会显示在右方
									fromid: fs[0].id,  //消息的发送者id（比如群组中的某个消息发送者），可用于自动解决浏览器多窗口时的一些问题
									timestamp: timestamp * 1000 - 8 * 60 * 60 * 1000 //服务端时间戳毫秒数。注意：如果你返回的是标准的 unix 时间戳，记得要 *1000
								}
								api.sendEvent({
									name: 'getChatMsg',
									extra: {
										msgObj: msgObj
									}
								});
								if (isOpenChatList) {
									api.sendEvent({
										name: 'checkChatList',
										extra: {
											msgObjArray: [msgObj]
										}
									});

								} else {
									that.setChatStorage([msgObj]);
									if (msg) {
										that.dot++;
									}

								}


								if (msg) {

									audioStreamer.onNormal();
									audioStreamer.openPlayer({
										path: 'widget://image/chat/msg.mp3',
									}, function (ret) {

									});
								}

							}
						}
						$.clientCallBacks["onGroupMsg"] = function (userId, groupId, msg, timestamp) {

							var getGroupList = function () {
								APP.ajax('getGroupList', { userID: APP.getUserInfo().UserID }, function (res) {
									groups = [];
									for (var i = 0; i < res.ds.length; i++) {
										groups.push({
											groupname: res.ds[i].GroupName,
											id: res.ds[i].GroupID.toString(),
											avatar: "../../image/ql.png" //群组头像
										})
									}
									onGroupMsgGet();
								})
							}

							var onGroupMsgGet = function () {
								var fs = [];
								for (var u in friend) {
									if (friend[u].id == userId) {
										fs.push(friend[u])
									}
								}
								var gs = [];
								for (var u in groups) {
									if (groups[u].id == groupId) {
										gs.push(groups[u])
									}
								}
								if (gs.length == 0) {
									getGroupList();
								}
								if (fs.length > 0) {
									//接收消息
									var msgObj = {
										groupname: gs[0].groupname,
										username: fs[0].username,
										avatar: fs[0].avatar,
										id: groupId,
										type: "group", //聊天窗口来源类型，从发送消息传递的to里面获取
										content: msg,
										cid: 0,  //消息id，可不传。除非你要对消息进行一些操作（如撤回）
										mine: false,  //是否我发送的消息，如果为true，则会显示在右方
										fromid: fs[0].id,  //消息的发送者id（比如群组中的某个消息发送者），可用于自动解决浏览器多窗口时的一些问题
										timestamp: timestamp * 1000 - 8 * 60 * 60 * 1000 //服务端时间戳毫秒数。注意：如果你返回的是标准的 unix 时间戳，记得要 *1000
									};


									api.sendEvent({
										name: 'getChatMsg',
										extra: {
											msgObj: msgObj
										}
									});

									if (isOpenChatList) {
										api.sendEvent({
											name: 'checkChatList',
											extra: {
												msgObjArray: [msgObj]
											}
										});
									} else {
										that.setChatStorage([msgObj]);
										if (msg) {
											that.dot++;
										}
									}


								}
							}

							onGroupMsgGet();
							if (msg) {
								audioStreamer.onNormal();
								audioStreamer.openPlayer({
									path: 'widget://image/chat/msg.mp3',
								}, function (ret) {

								});
							}



						}


						$.clientCallBacks["onUserOnlineNotify"] = function (info) {

						}

						$.clientCallBacks["onUserOfflineNotify"] = function (userId) {

						}

						signalRHelper();
						//获取未读信息
						setTimeout(function () {
							that.getUnReadMsg();
						}, 2000);
					})
				},
				setChatStorage: function (msgObjArray) {
					var that = this;
					var sql = "select * from Chat where UserID='" + APP.getUserInfo().UserID + "'";
					var chatPersonList_sql = DB.selectSqlSync(sql);
					if (chatPersonList_sql.length) {
						var chatPersonList = JSON.parse(chatPersonList_sql[0].JSONStr1);
						for (var i in msgObjArray) {
							if (msgObjArray[i].content) {
								if (msgObjArray[i].type == 'group') {
									msgObjArray[i].avatar = '../../image/ql.png';
								}
								var x = 0;
								for (var j in chatPersonList) {
									if (parseInt(chatPersonList[j].id) == parseInt(msgObjArray[i].id) && chatPersonList[j].type == msgObjArray[i].type) {
										x = 1;
										msgObjArray[i].unReadNum = (parseInt(chatPersonList[j].unReadNum) || 0) + 1;
										chatPersonList[j] = msgObjArray[i];
									}
								}
								if (x == 0) {
									msgObjArray[i].unReadNum = 1;
									chatPersonList.unshift(msgObjArray[i]);
								}
							}

						}

						var sql = "update Chat set JSONStr1='" + JSON.stringify(chatPersonList).replace(/\'/g, '\'\'') + "',UpdateTime='" + APP.getFormatDate() + "' where ChatID='" + chatPersonList_sql[0].ChatID + "'";
						DB.executeSql(sql, function () {

						})

					} else {
						var sql = "insert into Chat (UserID,JSONStr1,CreateTime) values ('" + APP.getUserInfo().UserID + "','" + JSON.stringify(msgObjArray).replace(/\'/g, '\'\'') + "','" + APP.getFormatDate() + "')"
						DB.executeSql(sql, function () {

						})
					}
				},
				getUnReadMsg: function () {
					var that = this;
					APP.ajax('getUnReadMsg', { userID: APP.getUserInfo().UserID }, function (res) {
						var unReadMsgObj = [];
						for (var i = 0; i < res.ds.length; i++) {
							//每条消息重新发送给当前用户
							var fs = [];
							for (var u in friend) {
								if (friend[u].id == res.ds[i].FromUserID) {
									fs.push(friend[u])
								}
							}
							if (fs.length > 0) {
								//接收消息
								var msgObj = {
									groupname: '',
									username: fs[0].username,
									avatar: fs[0].avatar,
									id: fs[0].id,
									type: "friend",  //聊天窗口来源类型，从发送消息传递的to里面获取
									content: res.ds[i].Content,
									cid: 0,  //消息id，可不传。除非你要对消息进行一些操作（如撤回）
									mine: false,  //是否我发送的消息，如果为true，则会显示在右方
									fromid: fs[0].id,  //消息的发送者id（比如群组中的某个消息发送者），可用于自动解决浏览器多窗口时的一些问题
									timestamp: res.ds[i].CreateTimeStamp * 1000 - 8 * 60 * 60 * 1000 //服务端时间戳毫秒数。注意：如果你返回的是标准的 unix 时间戳，记得要 *1000
								};

								unReadMsgObj.push(msgObj)

							}
						}
						for (var i = 0; i < res.ds1.length; i++) {
							var fs = [];
							for (var u in friend) {
								if (friend[u].id == res.ds1[i].FromUserID) {
									fs.push(friend[u])
								}
							}
							var gs = [];
							for (var u in groups) {
								if (groups[u].id == res.ds1[i].GroupID) {
									gs.push(groups[u])
								}
							}
							if (fs.length > 0) {
								//接收消息
								var msgObj = {
									groupname: gs[0].groupname,
									username: fs[0].username,
									avatar: fs[0].avatar,
									id: res.ds1[i].GroupID,
									type: "group",  //聊天窗口来源类型，从发送消息传递的to里面获取
									content: res.ds1[i].Content,
									cid: 0, //消息id，可不传。除非你要对消息进行一些操作（如撤回）
									mine: false,  //是否我发送的消息，如果为true，则会显示在右方
									fromid: fs[0].id,  //消息的发送者id（比如群组中的某个消息发送者），可用于自动解决浏览器多窗口时的一些问题
									timestamp: res.ds1[i].CreateTimeStamp * 1000 - 8 * 60 * 60 * 1000 //服务端时间戳毫秒数。注意：如果你返回的是标准的 unix 时间戳，记得要 *1000
								};

								unReadMsgObj.push(msgObj)

							}
						}

						if (isOpenChatList) {
							api.sendEvent({
								name: 'checkChatList',
								extra: {
									msgObjArray: unReadMsgObj
								}
							});
						} else {
							if (unReadMsgObj.length) {
								that.dot = unReadMsgObj.length;
								audioStreamer.onNormal();
								audioStreamer.openPlayer({
									path: 'widget://image/chat/msg.mp3',
								}, function (ret) {

								});
							}
						}

					})
				},
				changeTabbar: function (index) {
					var url = '';
					if (index == 0) {
						url = 'index';

					} else if (index == 1) {
						url = 'chat/chatList';
						this.tabbarActive = -1;
					} else if (index == 2) {
						url = 'personalCenter';
						// this.tabbarActive = -1;
					}

					if (index == 1) {
						api.openWin({
							name: url,
							url: url + '.html',
							reload: true,
							slidBackEnabled: false,
							allowEdit:true,
							pageParam: {
								historyData: null
							}
						})
					} else {
						api.openFrame({
							name: url,
							url: url + '.html',
							rect: {
								x: 0,
								y: 0,
								w: api.winWidth,
								h: api.winHeight - 50 - api.safeArea.bottom
							}
						});
					}


				}
			}
		})
	};
</script>

</html>